// pages/order/order.js
const app = getApp()
const auth = require('../../utils/auth')

Page({
  data: {
    selectedDate: '',
    selectedTime: 'dinner',
    dateList: [],
    timeOptions: [
      { id: 'breakfast', name: '早餐' },
      { id: 'lunch', name: '午餐' },
      { id: 'dinner', name: '晚餐' }
    ],
    category: 'all',
    categories: [
      { id: 'all', name: '推荐' },
      { id: '家常菜', name: '家常菜' },
      { id: '汤羹', name: '汤羹' },
      { id: '主食', name: '主食' },
      { id: '西餐', name: '西餐' }
    ],
    dishList: [],
    filteredList: [],
    selectedDishes: [],
    showPlan: false,
    planNote: '',
    isAuthenticated: false,
    currentUser: null
  },

  onLoad() {
    this.checkAuthentication()
    this.initDates()
    this.loadDishes()
  },

  onShow() {
    this.checkAuthentication()
  },

  // 检查认证状态
  checkAuthentication() {
    // 首先检查是否已经有认证状态
    const currentUser = auth.getCurrentUser()
    if (currentUser) {
      this.setData({
        isAuthenticated: true,
        currentUser: currentUser
      })
      return
    }
    
    // 如果没有认证状态，重新检查
    auth.checkAuthentication()
      .then(user => {
        auth.setCurrentUser(user)
        this.setData({
          isAuthenticated: true,
          currentUser: user
        })
      })
      .catch(err => {
        this.setData({
          isAuthenticated: false,
          currentUser: null
        })
        wx.showModal({
          title: '需要身份验证',
          content: '使用计划功能需要先进行身份验证',
          showCancel: false,
          success: () => {
            wx.switchTab({
              url: '/pages/home/home'
            })
          }
        })
      })
  },

  // 初始化日期列表
  initDates() {
    const dates = []
    const today = new Date()
    
    for (let i = 0; i < 7; i++) {
      const date = new Date(today)
      date.setDate(today.getDate() + i)
      
      dates.push({
        date: this.formatDate(date),
        name: i === 0 ? '今天' : (i === 1 ? '明天' : this.formatWeek(date)),
        fullDate: date
      })
    }
    
    this.setData({
      dateList: dates,
      selectedDate: dates[0].date
    })
  },

  formatDate(date) {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
  },

  formatWeek(date) {
    const weeks = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
    return weeks[date.getDay()]
  },

  // 加载菜品列表
  loadDishes() {
    const db = wx.cloud.database()
    db.collection('dishes')
      .orderBy('createTime', 'desc')
      .get()
      .then(res => {
        this.setData({
          dishList: res.data
        })
        this.filterDishes()
      })
      .catch(err => {
        console.error('加载菜品失败：', err)
        wx.showToast({
          title: '加载失败',
          icon: 'none'
        })
      })
  },

  // 选择日期
  onDateSelect(e) {
    const date = e.currentTarget.dataset.date
    this.setData({ selectedDate: date })
  },

  // 选择餐次
  onTimeSelect(e) {
    const time = e.currentTarget.dataset.time
    this.setData({ selectedTime: time })
  },

  // 选择分类
  onCategorySelect(e) {
    const category = e.currentTarget.dataset.category
    this.setData({ category })
    this.filterDishes()
  },

  // 筛选菜品
  filterDishes() {
    let { dishList, category, selectedDishes } = this.data
    let filteredList = [...dishList]
    
    if (category !== 'all') {
      filteredList = filteredList.filter(item => item.category === category)
    }
    
    // 添加选中状态
    filteredList = filteredList.map(item => {
      return {
        ...item,
        isSelected: selectedDishes.some(d => d._id === item._id)
      }
    })
    
    this.setData({ filteredList })
  },

  // 选择菜品
  onDishSelect(e) {
    const dish = e.currentTarget.dataset.dish
    const index = this.data.selectedDishes.findIndex(item => item._id === dish._id)
    
    if (index > -1) {
      // 取消选择
      const selectedDishes = [...this.data.selectedDishes]
      selectedDishes.splice(index, 1)
      this.setData({ selectedDishes }, () => {
        this.filterDishes()
      })
    } else {
      // 添加选择
      this.setData({
        selectedDishes: [...this.data.selectedDishes, {
          ...dish,
          note: '',
          quantity: 1
        }]
      }, () => {
        this.filterDishes()
      })
    }
  },

  // 更新菜品备注
  onDishNoteChange(e) {
    const { index } = e.currentTarget.dataset
    const note = e.detail.value
    this.setData({
      [`selectedDishes[${index}].note`]: note
    })
  },

  // 从购物车移除
  removeFromCart(e) {
    const { index } = e.currentTarget.dataset
    const selectedDishes = [...this.data.selectedDishes]
    selectedDishes.splice(index, 1)
    this.setData({ selectedDishes }, () => {
      this.filterDishes()
    })
  },

  // 显示/隐藏计划
  togglePlan() {
    this.setData({
      showPlan: !this.data.showPlan
    })
  },

  // 计划备注输入
  onPlanNoteInput(e) {
    this.setData({
      planNote: e.detail.value
    })
  },

  // 提交计划
  submitPlan() {
    if (this.data.selectedDishes.length === 0) {
      wx.showToast({
        title: '请选择菜品',
        icon: 'none'
      })
      return
    }
    
    if (!this.data.isAuthenticated) {
      wx.showModal({
        title: '需要身份验证',
        content: '请先进行身份验证',
        showCancel: false
      })
      return
    }
    
    const db = wx.cloud.database()
    const order = {
      orderNo: this.generateOrderNo(),
      date: this.data.selectedDate,
      time: this.data.selectedTime,
      dishes: this.data.selectedDishes,
      note: this.data.planNote,
      status: 'pending',
      userName: this.data.currentUser.nickName,
      userAvatar: this.data.currentUser.avatarUrl,
      createTime: db.serverDate()
    }
    
    db.collection('orders')
      .add({
        data: order
      })
      .then(res => {
        // 添加订单ID到订单对象
        const completeOrder = {
          ...order,
          _id: res._id
        }
        
        // 通知功能已移除
        console.log('订单创建成功:', completeOrder.orderNo)
        
        wx.showToast({
          title: '订单创建成功',
          icon: 'success'
        })
        
        // 清空选择
        this.setData({
          selectedDishes: [],
          planNote: '',
          showPlan: false
        }, () => {
          this.filterDishes()
        })
        
        // 跳转到计划管理
        setTimeout(() => {
          wx.redirectTo({
            url: '/pages/orders/orders'
          })
        }, 1500)
      })
      .catch(err => {
        console.error('创建计划失败：', err)
        wx.showToast({
          title: '创建失败',
          icon: 'none'
        })
      })
  },

  // 生成订单号
  generateOrderNo() {
    const date = new Date()
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
    return `${year}${month}${day}${random}`
  },

  // 跳转到身份验证
  goToAuth() {
    wx.switchTab({
      url: '/pages/home/home'
    })
  }
})